# -*- coding: utf-8 -*-

import pika
from rabbitmq import RabbitConnection
from rabbitmq.config import *


def send_task(channel, request_id, timeout):
    # # 声明死信队列
    exchange_arguments = {
        'x-delayed-type': 'direct'
    }
    channel.exchange_declare(
        exchange=dead_exchange, durable=False, exchange_type=delay_exchange_type, arguments=exchange_arguments
    )
    channel.queue_declare(queue=dead_queue_name, durable=False)
    channel.queue_bind(queue=dead_queue_name, exchange=dead_exchange, routing_key=dead_routing_key)

    # 延迟队列声明
    # 死信转发参数
    arguments = {
        # 通过x-message-ttl 指定整个队列所有消息过期时间, 单位毫秒
        "x-message-ttl": 1,
        'x-delayed-type': 'direct',
        'x-dead-letter-exchange': dead_exchange,
        'x-dead-letter-routing-key': dead_routing_key
    }
    # 指定交换机
    exchange_arguments = {
        'x-delayed-type': 'direct'
    }
    channel.exchange_declare(
        exchange=delay_exchange, durable=False, exchange_type=delay_exchange_type, arguments=exchange_arguments
    )
    # 如果指定的queue不存在，则会创建一个queue，如果已经存在 则不会做其他动作，官方推荐，每次使用时都可以加上这句
    channel.queue_declare(queue=delay_queue_name, durable=False, arguments=arguments)
    # 队列绑定交换机
    channel.queue_bind(queue=delay_queue_name, exchange=delay_exchange, routing_key=delay_routing_key)

    # 发送信息
    channel.basic_publish(
        exchange=delay_exchange,
        routing_key=delay_routing_key,
        body=request_id,
        # 基于交换机
        properties=pika.BasicProperties(delivery_mode=2, headers={'x-delay': timeout})
    )
    return channel


if __name__ == "__main__":
    rabbit = RabbitConnection()
    channel = rabbit.get_connection()
    # 3秒过期， 单位：毫秒
    channel = send_task(channel, '延迟3s', 3000)
    channel = send_task(channel, '延迟10s', 10000)
    channel = send_task(channel, '延迟30s', 30000)
    channel = send_task(channel, '延迟5s', 5000)
    print(123456)
    # 关闭连接
    rabbit.connection.close()
